package org.giovanolli.mumi.controller.business;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;

import org.giovanolli.mumi.util.DateUtils;
import org.giovanolli.mumi.view.util.FacesContextUtils;
import org.springframework.stereotype.Controller;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;

/**
 * The Class ReportController.
 */
@Controller("reportController")
public class ReportController {

	/**
	 * Format page.
	 * 
	 * @param document
	 *            the document
	 */
	private final void formatPage(Document document) {
		document.setPageSize(PageSize.A4);
	}

	/**
	 * Generate header.
	 * 
	 * @return the table
	 * @throws BadElementException
	 *             the bad element exception
	 * @throws MalformedURLException
	 *             the malformed url exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	private final Table generateHeader() throws BadElementException, MalformedURLException, IOException {
		Table header = new Table(2);
		header.setBorderWidth(Rectangle.NO_BORDER);
		header.setPadding(2f);

		// Logo cell
		Cell logoCell = getFormattedForHeaderCell();
		String logoPath = FacesContextUtils.getRealPath() + File.separator + "resources" + File.separator + "images" + File.separator + "logo_90_45.png";
		logoCell.add(Image.getInstance(logoPath));
		header.addCell(logoCell);

		// Title cell
		Cell titleCell = getFormattedForHeaderCell();
		titleCell.add(new Chunk("Listado"));
		header.addCell(titleCell);

		// Date Cell
		Cell reportDateCell = getFormattedForHeaderCell();
		String reportDate = DateUtils.getSimpleFormattedDate(new Date());
		reportDateCell.add(new Chunk(reportDate));
		header.addCell(reportDateCell);
		return header;
	}

	/**
	 * Gets the formatted for header cell.
	 * 
	 * @return the formatted for header cell
	 */
	private final Cell getFormattedForHeaderCell() {
		Cell rv = new Cell();
		rv.setBorder(Rectangle.NO_BORDER);
		rv.setHorizontalAlignment("Center");
		rv.setVerticalAlignment("Center");
		return rv;
	}

	/**
	 * Pre process pdf.
	 * 
	 * @param document
	 *            the document
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 * @throws BadElementException
	 *             the bad element exception
	 * @throws DocumentException
	 *             the document exception
	 */
	public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException {
		Document pdf = (Document) document;
		pdf.open();
		this.formatPage(pdf);
		pdf.add(this.generateHeader());
	}
}
